#include <stdio.h>
#include <time.h>
#include <math.h>
#include "rs485cmdque.h"

static RSRTUCMD items[MAX_QUE_LEN];
static int front = -1;
static int rear = -1;

int RsCmdQueIsFull()
{
    if ((rear + 1) % MAX_QUE_LEN == front)
        return 1;
    return 0;
}

int RsCmdQueReset()
{
    rear = -1;
    front = -1;
    memset(items, 0, MAX_QUE_LEN * sizeof(RSRTUCMD));
    return 0;
}
int RsCmdQueIsEmpty()
{
    if (front == -1)
        return 1;
    return 0;
}

short RsCmdEnqueue(RSRTUCMD element)
{
    if (RsCmdQueIsFull())
    {
        return -1;
    }
    else
    {
        if (front == -1)
            front = 0;
        rear = (rear + 1) % MAX_QUE_LEN;
        items[rear] = element;
        // int queSize = RsCmdQueSize();
        // printf("command queue size: %d\n", queSize);
    }
    return 0;
}

short RsCmdDequeue(RSRTUCMD* pElement)
{
    if (pElement == NULL)
        return -1;
    if (RsCmdQueIsEmpty())
    {
        return -1;
    }
    else
    {
        *pElement = items[front];
        if (front == rear)
        {
            front = -1;
            rear = -1;
        }
        else
        {
            front = (front + 1) % MAX_QUE_LEN;
        }
        return 0;
    }
}

RSRTUCMD* RsCmdQuePeek()
{
    if (RsCmdQueIsEmpty())
    {
        return NULL;
    }
    return &items[front];
}

int RsCmdQueSize()
{
    if (front == -1)
    {
        return 0;
    }
    int size = ((rear + MAX_QUE_LEN - front) % MAX_QUE_LEN);
    return size + 1;
}
